#!/usr/bin/env python3
# -*- coding: utf-8 -*-
from flask import Blueprint

from APP import socketio
import re
import json
from datetime import datetime
from flask import current_app
from InfluxDB_setting.api.parse_lynis import parse_lynis_log
from InfluxDB_setting.api.generate_llm_report import (
    extract_metadata, 
    calculate_security_score, 
    classify_vulnerabilities,
    generate_llm_report,
    convert_markdown_to_text
)
generate = Blueprint('generate', __name__)
def generate_combined_report():
    """生成整合报告并返回JSON格式"""
    
    try:
        # 解析lynis.log文件
        vulnerabilities = parse_lynis_log("./lynis.log")
        
        if not vulnerabilities:
            return {
                "message": "Failed",
                "code": 400,
                "data": {
                    "loopList": [],
                    "endCon": {
                        "loading": False,
                        "scanPaperMarkdown": "未找到任何漏洞信息",
                        "scanPaper": "未找到任何漏洞信息"
                    }
                }
            }
        
        # 读取日志文件内容
        try:
            with open("./lynis.log", "r", encoding="utf-8") as f:
                log_content = f.read()
        except FileNotFoundError:
            return {
                "message": "Failed",
                "code": 400,
                "data": {
                    "loopList": [],
                    "endCon": {
                        "loading": False,
                        "scanPaperMarkdown": "错误: 找不到lynis.log文件",
                        "scanPaper": "错误: 找不到lynis.log文件"
                    }
                }
            }
        
        # 生成LLM报告
        markdown_report = generate_llm_report(vulnerabilities, log_content)
        
        # 转换为纯文本格式
        text_report = convert_markdown_to_text(markdown_report)
        
        # 构建返回的JSON数据
        result = {
            "message": "Success",
            "code": 200,
            "data": {
                "loopList": vulnerabilities,
                "endCon": {
                    "loading": False,
                    "scanPaperMarkdown":
                        markdown_report,
                    "scanPaper":
                        text_report
                }
            }
        }
        
        return result
        
    except Exception as e:
        return {
            "message": "Failed",
            "code": 400,
            "data": {
                "loopList": [],
                "endCon": {
                    "loading": False,
                    "scanPaperMarkdown": f"生成报告时出错: {str(e)}",
                    "scanPaper": f"生成报告时出错: {str(e)}"
                }
            }
        }

@socketio.on('client_server3')
def main(message):
    try:

        """主函数"""
        print(message)
        print("正在生成整合报告...")

        # 生成整合报告
        result = generate_combined_report()
        socketio.emit('alert_update3',json.dumps(result, ensure_ascii=False, indent=2))
        # 在控制台输出JSON格式
        # print("\n" + "="*50)
        # print("整合报告JSON输出")
        # print("="*50)
        print(json.dumps(result, ensure_ascii=False, indent=2))

        # 保存JSON到文件
        # with open("combined_report.json", "w", encoding="utf-8") as f:
        #     json.dump(result, f, ensure_ascii=False, indent=2)

        # print(f"\n报告已保存到 combined_report.json 文件")

        # 显示统计信息
        # if result["code"] == 200:
        #     vulnerabilities_count = len(result["data"]["loopList"])
        #     print(f"\n统计信息:")
        #     print(f"- 漏洞数量: {vulnerabilities_count}")
        #     print(f"- 报告状态: {result['message']}")
        #     print(f"- 状态码: {result['code']}")
    except Exception as e:
        import traceback
        traceback.print_exc()  # 打印完整堆栈信息
        current_app.logger.error(f"处理client_server3出错: {str(e)}")
